package com.xlh.enums;

import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字节存储单位枚举
 *
 * @author cheer
 */
public enum ByteUnitEnum {

    B,
    KB,
    MB,
    GB,
    TB;


    private static final Pattern pattern = Pattern.compile("^(\\d+)([KMGT]?B)$");

    /**
     * 将4MB，8GB这样的可读存储大小转换成字节大小
     * 例如：8GB 转换为
     *
     * @param unit 可读存储大小
     * @return 字节数
     */
    public static long unitToBytes(String unit) {
        Matcher matcher = pattern.matcher(StringUtils.deleteWhitespace(unit));
        if (matcher.matches()) {
            int number = Integer.parseInt(matcher.group(1));
            String byteUnit = matcher.group(2);
            for (ByteUnitEnum byteUnitEnum : ByteUnitEnum.values()) {
                if (Objects.equals(byteUnitEnum.name(), byteUnit)) {
                    return (long) number * (2 << (10 * byteUnitEnum.ordinal() - 1));
                }
            }
        }
        return 0;
    }
}
